<?php

declare(strict_types=1);

namespace App\Robot\Job;

use Carbon\Carbon;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;

class DelayedTaskJob extends Job
{
    public array $data;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        logger()->info('执行时间'.Carbon::now()->toDateTimeString());
        $logger = container()->get(LoggerInterface::class);
        $logger->info("延迟任务处理中...",[
            'time' => Carbon::now()->toDateTimeString()
        ]);
        try {
            // 模拟任务处理逻辑
            if (rand(0, 1)) {
                throw new \Exception("Simulated task failure");
            }

            $logger->info("Task processed successfully", ['data' => $this->data]);

        } catch (\Exception $e) {
            $logger->error("Task processing failed", [
                'data' => $this->data,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }

    public function failed(array $data, \Throwable $exception)
    {
        $logger = container()->get(LoggerInterface::class);

        $logger->critical("Task failed after max retries", [
            'data' => $data,
            'error' => $exception->getMessage(),
        ]);

        $this->sendAlert($data);
    }

    protected function sendAlert(array $data)
    {
        echo "Alert: Task has failed after maximum retries.\n";
    }
}